package com.leetcode.LeetCode精选TOP面试题;

/**
 * @author 覃国强
 * @date 2022-07-04 17:21
 */
public class 题库_0162_寻找峰值 {

  public static void main(String[] args) {
    int[] nums = {1,2};
    Solution solution = new Solution();
    int index = solution.findPeakElement(nums);
    System.out.println(index);
  }


  static
  class Solution {
    public int findPeakElement(int[] nums) {
      if (nums == null || nums.length == 0) {
        return -1;
      }
      if (nums.length == 1) {
        return 0;
      }
      int left = 0;
      int right = nums.length - 1;
      while (left <= right) {
        int middle = (left + right) / 2;

        if (middle == 0) {
          // 左边界
          if (nums[middle] > nums[middle + 1]) {
            return middle;
          } else {
            left = middle + 1;
          }
        } else if (middle == nums.length - 1) {
          // 右边界
          if (nums[middle] > nums[middle - 1]) {
            return middle;
          } else {
            right = middle - 1;
          }
        } else {
          // 正常情况
          if (nums[middle - 1] < nums[middle] && nums[middle] > nums[middle + 1]) {
            return middle;
          } else if (nums[middle] < nums[middle + 1]) {
            left = middle + 1;
          } else {
            right = middle - 1;
          }
        }
      }
      return -1;
    }
  }


}
